package com.example.demo.controller;


import com.example.demo.common.Result;
import com.example.demo.entity.Menu;
import com.example.demo.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wms
 * @since 2022-10-04
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;
    @GetMapping("/list")
    public Result list(@RequestParam String roleId){
        List list = menuService.lambdaQuery().like(Menu::getMenuright,roleId).list();
        return Result.suc(list);
    }
    @GetMapping("/Menulist")
    public Result menuList(@RequestParam("roleId") String roleId){
        List<Menu> list = menuService.lambdaQuery().like(Menu::getMenuright,roleId).list();
        List<Menu> menuTree = builderMenuTree(list);
        return Result.suc(menuTree);

    }

    private List<Menu> builderMenuTree(List<Menu> list) {
        List<Menu> menuTree = list.stream()
                .filter(menu -> menu.getMenulevel().equals("0"))
                .map(menu -> menu.setChildren(getChildren(menu, list)))
                 .collect(Collectors.toList());
return  menuTree;
    }

    private List<Menu> getChildren(Menu menu, List<Menu> menus) {
        List<Menu> childrenList = menus.stream()
                .filter(m -> m.getMenuparentcode().equals(menu.getMenucode()))
                .collect(Collectors.toList());
        return childrenList;
    }
}


